<template>
  <div class="box">
    <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:getPath}">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div style="margin-top: 15px;">
        <el-input placeholder="请输入用户名"  class="input-with-select" 
         :clearable="true"  @clear="getUserList"
         v-model="queryInfo.query">
          <el-button slot="append" icon="el-icon-search" :disabled="!queryInfo.query" @click="getUserList">
          </el-button>
        </el-input>
        <el-button type="primary" icon="el-icon-plus" style="margin-left:15px" @click="addUser">添加用户</el-button>
      </div>
      <!-- 表格 -->
      <el-table style="width: 100%" border :data="userList.users">
        <el-table-column prop="prop" label="#" width="30" type="index">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="80">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="width">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="width">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="100">
        </el-table-column>
        <el-table-column prop="prop" label="状态" width="80">
          <template v-slot={row}>
            <el-switch v-model="row.mg_state" @change="changeSwitch(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="width">
          <template v-slot="{row}">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUser(row)">
            </el-button>
            <el-button type="warning" size="mini" title="分配角色" icon="el-icon-star-off" @click="shareRole(row)">
            </el-button>
            <el-button type="danger"  size="mini" icon="el-icon-delete" @click="open(row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
       <el-pagination
          align="center"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1,3,6]"
          :page-size="1"
          :pager-count="5"
          layout="  jumper,prev, pager, next, total,sizes"
          :total="userList.total"
          @current-change="getUserList"
          @size-change="handleSizeChange">
      </el-pagination>

      <!-- 添加按钮和修改按钮 显示的对话框 :before-close="handleClose"-->
      <el-dialog :title="scence==0 ?'添加用户': '修改用户信息'" :visible.sync="dialogVisible" width="40%" @close="closeDialog">
        <el-form ref="ruleForm" label-width="100px" :rules="Userrules" :model="addUserInfo">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserInfo.username" :disabled="scence!=0"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="scence == 0">
            <el-input v-model="addUserInfo.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUserInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="addSaveUser">保存</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色按钮的对话框 -->
      <el-dialog title="分配角色" :visible.sync="shareRoleDialog" @close="closeRoleDialog" width="width">
        <p>当前的角色：{{userRoleInfo.username}}</p>
        <p>当前的用户：{{userRoleInfo.role_name}}</p>
        <p>分配新角色：
            <el-select placeholder="请选择" v-model="roleId">
              <el-option :label="item.roleName" :value="item.id"  v-for="item in roleList" :key="item.id">
              </el-option>
            </el-select>
        </p>
        <div slot="footer">
          <el-button @click="shareRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRole" :disabled="!roleId">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
    name: 'user',
    data(){
      // 自定义邮箱的验证规则
      var checkEmail = (rule,value,callbacl)=>{
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        // 如果验证成功
        if(regEmail.test(value)){
          return callbacl()
        }
        callbacl(new Error('请输入正确的邮箱'))
      }
      // 自定义手机号码规则
      var checkMobile = (rule,value,callbacl) =>{
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}/
        if(regMobile.test(value)){
          return callbacl()
        }
        callbacl(new Error('请输入正确的手机号码'))
      }
      return{
        // 存储用户列表数据
        userList:{},
        // 收集发请求用户列表请求的参数
        queryInfo:{
          query:'',
          pagenum: 3,
          pagesize:3
        },
        // 控制对话框显示
        dialogVisible:false,
        // 储存添加用户 的 信息
        addUserInfo:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        // 控制添加按钮和修改按钮 弹出的对话框 展示不同的内容
        scence:0,
        // 保存要修改的用户 ID
        editUserId:'',
        // 表单验证规则
        Userrules:{
          username: [
            { required: true, message: '请输入你的用户名', trigger: 'blur' },
            { min: 3,max:7, message: '请输入3到7位数的用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入你的密码', trigger: 'blur' },
            { min: 6,max:16, message: '请输入6到16位数的密码', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请求输入你的邮箱', trigger: 'blur' },
            {validator:checkEmail,trigger: 'blur'}
          ],
          mobile: [
            { required: true, message: '请输入你的手机号码', trigger: 'blur'},
            {validator:checkMobile,trigger: 'blur' }
          ],
        },
        // 控制分配角色的对话框
        shareRoleDialog: false,
        // 收集分配权限的信息
        userRoleInfo:{},
        // 储存角色数据
        roleList:[],
        // 储存选择器选中的角色ID
        roleId:''
      }
    },
    methods:{
      // 获取用户列表数据
      async getUserList(pager=1){
        // 当前页默认为1，当分页器当前页改变时，为当前页数
        this.queryInfo.pagenum = pager
        this.queryInfo.pagesize = 3
        if(this.queryInfo.query != ''){
          this.queryInfo.pagesize = 1
          this.queryInfo.pagenum = 1
        }
        let {data:result} = await this.$API.get('users',{params:this.queryInfo})
        if(result.meta.status == 200){
          this.userList = result.data
        }
      },
        // 每条页数改变时
      handleSizeChange(sizes){
        this.queryInfo.pagesize = sizes
        // 刷新列表数据
        this.getUserList()
      },
      // switch状态改变的回调函数
      async changeSwitch(row){
        let {data:result} = await this.$API.put(`users/${row.id}/state/${row.mg_state}`)
        if(result.meta.status == 200){
          this.$message.success('修改状态成功')
        }else{
          // 修改失败取反
          row.mg_state = !row.mg_state
        }
      },
      // 添加用户按钮
      addUser(){
        this.scence = 0
        this.dialogVisible = true
      },
      // 关闭对话框的回调
      closeDialog(){
        this.$refs.ruleForm.resetFields()
      },
      // 添加按钮和修改按钮的对话框保存按钮
      addSaveUser(){
        this.dialogVisible = false
        this.$refs.ruleForm.validate(async vali =>{
          if(!vali) return
          // 全部通过表单验证，则发起保存请求
          if(vali){
             if(this.scence == 0){
                // 发起添加用户信息请求
                let {data:result} = await this.$API.post('users',this.addUserInfo) 
                if(result.meta.status == 201){
                    // 刷新用户列表数据
                    this.getUserList()
                    return this.$message.success('添加成功')
                }else{
                    return this.$message.Error('添加失败')
                }
             }
             if(this.scence ==1 ){
              // 发起修改用户信息请求
                let {data:result} = await this.$API.put(`users/${this.editUserId}`,{email:this.addUserInfo.email,mobile:this.addUserInfo.mobile})
                if(result.meta.status == 200){
                    // 刷新用户列表数据
                    this.getUserList()
                    return this.$message.success('修改成功')
                }else{
                  return this.$message.Error('修改失败')
                }
             }
            
          }
        })
      },
      // 对话框取消按钮
      cancel(){
        this.dialogVisible = false
      },
      // 修改用户按钮
      editUser(row){
        console.log(row)
        this.dialogVisible = true
        this.scence = 1
        this.editUserId = row.id
        this.addUserInfo.username = row.username
        this.addUserInfo.mobile = row.mobile
        this.addUserInfo.email = row.email
      },
      // 删除按钮
      open(row){
         this.$confirm(`是否删除${row.username}用户`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let {data:result} = await this.$API.delete(`users/${row.id}`)
          console.log(result)
          if(result.meta.status == 200){
              // 更新用户列表
              this.getUserList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
          }else{
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })   
           }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })       
        });
      },
      // 分配角色按钮
      async shareRole(row){
        this.shareRoleDialog = true
        // 获取要展示到对话框的内容
        this.userRoleInfo = row
        // 发起角色数据请求
        let {data:result} = await this.$API.get('roles')
        if(result.meta.status == 200 ){
          this.roleList = result.data
        }
      },
      // 分配角色对话框的确定按钮
      async saveRole(){
        // 发起分配角色确定请求
        let {data:result} = await this.$API.put(`users/${this.userRoleInfo.id}/role`,{rid:this.roleId})
        this.shareRoleDialog = false
        if(result.meta.status !=200){
          return this.$message.Error('分配角色失败')
        }
        this.$message.success('分配角色成功')
        this.getUserList()
      },
      // 关闭分配角色对话框的回调
      closeRoleDialog(){
        // 清空上次要展示到对话框的内容
        this.userRoleInfo = {}
        // 清空上次角色数据
        this.roleList = [],
        // 清空选择器选中的值的id
        this.roleId = ''
      }
    },
    computed:{
      // 给面包屑导航当前的路由
      getPath(){
        return this.$route.path 
      }
    },
    mounted(){
      this.getUserList()
    }
}
</script>

<style lang="less">
.el-input{
    width: 300px;
}
.el-table{
  margin-top: 20px;
}
.el-pagination{
  margin:20px 0;
}
</style>